<template>
  <div class="personal-info">
    <el-row>
      <el-col style="display: flex" class="carduserinfo">
        <el-card class="box-card">
          <div class="user_info">
            <img :src="userInfoObj.avatar" />
            <div class="userinfo">
              <p class="name">{{ userInfoObj.nickName }}，欢迎使用。</p>
              <p class="access">角色：{{ userInfoObj.roles }}</p>
            </div>
          </div>
          <div class="login-info">
            <p>
              当前账号：<span>{{ userInfoObj.userName }}</span>
            </p>
          </div>
        </el-card>
        
        <el-card>
          <div id="maintotal" style="width: 500px; height: 400px"></div>
        </el-card>

        <el-card>
          <div
            class="articlehot"
            ref="chart"
            style="width: 500px; height: 400px"
          ></div>
        </el-card>
      </el-col>
      <el-col>
        <el-card>
          <div class="charttotal" ref="chartTotal" style="width: 100%; height: 380px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { mapGetters } from "vuex";
import UserApi from "@/api/dashboard/dashboard";
export default {
  name: "Dashboard",
  computed: {
    ...mapGetters(["name"]),
  },
  data() {
    return {
      
      chartData: {
        dates: [],
        comments: [],
        articles: [],
        regitsters: [],
        tags: [],
        categoryes: [],
        talkes: [],
      },

      userInfoObj: "", //个人信息
      userInfo: {}, //本地存储的用户信
      cortayle: 80,
      dataList: [
        {
          name: "文章总数",
          value: "",
          icon: "el-icon-s-order",
          class: "article",
          color: "red",
        },
        {
          name: "用户总数",
          value: "",
          icon: "el-icon-user-solid",
          class: "user",
          color: "green",
        },
        {
          name: "评论总数",
          value: "",
          icon: "el-icon-chat-round",
          class: "comment",
          color: "blue",
        },
        {
          name: "链接总数",
          value: "",
          icon: "el-icon-position",
          class: "link",
          color: "orange",
        },
      ],
    };
  },
  mounted() {
    this.renderChart();
    this.renderChartArticle();
    this.renderStackedLineChart();
    this.getCommentS();
    this.getArticleS();
    this.getRegister();
    this.getTags();
    this.getCategorys();
    this.getTalkS();
  },
  methods: {
    fetchData() {
      UserApi.getTotal()
        .then((response) => {
          this.dataList.forEach((item) => {
            switch (item.name) {
              case "文章总数":
                item.value = response.articleCount;
                break;
              case "用户总数":
                item.value = response.userCount;
                break;
              case "评论总数":
                item.value = response.commentCount;
                break;
              case "链接总数":
                item.value = response.linkCount;
                break;
              default:
                break;
            }
          });
          this.renderChart();
        })
        .catch((error) => {
          console.error("Error fetching data", error);
        });
    },
    renderChart() {
      const chartDom = document.getElementById("maintotal");
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: "总数据浏览",
        },
        // Echarts配置选项
        tooltip: {
          trigger: "item",
        },
        legend: {
          top: "5%",
          left: "center",
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: this.dataList.map((item) => ({
              value: item.value,
              name: item.name,
            })),
          },
        ],
      };
      myChart.setOption(option);
    },

    //文章的前五热度
    renderChartArticle(data) {
      const chartDomArticle = this.$refs.chart;
      const myChartArticle = echarts.init(chartDomArticle);

      const chartData = data
        ? data.map((item) => ({
            name: item.title,
            value: item.viewCount,
          }))
        : [];

      const option = {
        title: {
          text: "最热文章浏览",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        series: [
          {
            name: "文章浏览量",
            type: "pie",
            radius: "55%",
            center: ["50%", "50%"],
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };

      myChartArticle.setOption(option);
    },

    //查询个人信息展示
    getUser() {
      UserApi.UserInfo()
        .then((response) => {
          // console.log(response);
          this.userInfoObj = response;
        })
        .catch((error) => {
          console.error(error);
        });
    },

    getArticlefive() {
      UserApi.getArticleHot().then((response) => {
        const data = response;
        // console.log(data);
        // 使用获取到的数据来生成饼图
        this.renderChartArticle(data);
      });
    },
    //评论日总数
    getCommentS() {
      UserApi.getCommentWeek().then((response) => {
        const backendDates = response.map((item) => item.commentDate);

        this.chartData.dates = this.generateDates();
        this.chartData.comments = this.chartData.dates.map((date) => {
          const index = backendDates.indexOf(date);
          return index !== -1 ? response[index].count : 0;
        });

        this.renderStackedLineChart();
      });
    },
    renderStackedLineChart() {
      const chartDom = this.$refs.chartTotal;
      const myChart = echarts.init(chartDom);

      const option = {
        title: {
          text: "一个月数据浏览",
        },
        legend: {
          data: [
            "评论日总数",
            "文章日总数",
            "用户注册日总数",
            "标签增加总数",
            "分类增加总数",
            "动态数据总数",
          ],
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: this.chartData.dates,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "评论日总数",
            type: "line",
            data: this.chartData.comments,
          },
          {
            name: "文章日总数",
            type: "line",
            data: this.chartData.articles,
          },
          {
            name: "用户注册日总数",
            type: "line",
            data: this.chartData.regitsters,
          },
          {
            name: "标签增加总数",
            type: "line",
            data: this.chartData.tags,
          },
          {
            name: "分类增加总数",
            type: "line",
            data: this.chartData.categoryes,
          },
          {
            name: "动态数据总数",
            type: "line",
            data: this.chartData.talkes,
          },
        ],
      };

      myChart.setOption(option);
    },

    //文章日总数
    getArticleS() {
      UserApi.getArticleWeek().then((response) => {
        const backendDates = response.map((item) => item.articleDate);

        this.chartData.dates = this.generateDates();
        this.chartData.articles = this.chartData.dates.map((date) => {
          const index = backendDates.indexOf(date);
          return index !== -1 ? response[index].count : 0;
        });

        this.renderStackedLineChart();
      });
    },

    //用户日注册总数
    getRegister() {
      UserApi.getRegisterWeek().then((response) => {
        const backendDates = response.map((item) => item.registerDate);
        // console.log(response);

        this.chartData.dates = this.generateDates();
        this.chartData.regitsters = this.chartData.dates.map((date) => {
          const index = backendDates.indexOf(date);
          return index !== -1 ? response[index].count : 0;
        });

        this.renderStackedLineChart();
      });
    },

    //标签增加总数
    getTags() {
      UserApi.getTagWeek().then((response) => {
        const backendDates = response.map((item) => item.tagDate);
        this.chartData.dates = this.generateDates();
        this.chartData.tags = this.chartData.dates.map((date) => {
          const index = backendDates.indexOf(date);
          return index !== -1 ? response[index].count : 0;
        });
        this.renderStackedLineChart();
      });
    },

    //分类增加总数
    getCategorys() {
      UserApi.getCategoryWeek().then((response) => {
        const backendDates = response.map((item) => item.categoryDate);
        this.chartData.dates = this.generateDates();
        this.chartData.categoryes = this.chartData.dates.map((date) => {
          const index = backendDates.indexOf(date);
          return index !== -1 ? response[index].count : 0;
        });
        this.renderStackedLineChart();
      });
    },
    getTalkS() {
      UserApi.getTalkWeek()
        .then()
        .then((response) => {
          const backendDates = response.map((item) => item.talkDate);
          this.chartData.dates = this.generateDates();
          this.chartData.talkes = this.chartData.dates.map((date) => {
            const index = backendDates.indexOf(date);
            return index !== -1 ? response[index].count : 0;
          });
          this.renderStackedLineChart();
        });
    },

    //时间转换
    generateDates() {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth();
      const dates = [];

      const firstDayOfMonth = new Date(year, month, 1);
      const lastDayOfMonth = new Date(year, month + 1, 0);

      for (
        let i = firstDayOfMonth.getDate();
        i <= lastDayOfMonth.getDate();
        i++
      ) {
        const date = new Date(year, month, i);
        const formattedDate = `${date.getFullYear()}-${String(
          date.getMonth() + 1
        ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
        dates.push(formattedDate);
      }

      return dates;
    },
  },
  created() {
    this.getUser();
    this.getArticlefive();
    this.fetchData();
  },
};
</script>

<style lang="scss" scoped>
@media screen and (max-width: 767px) {
  .carduserinfo {
    flex-direction: column;
  }
  #maintotal{
    width: 100% !important;
  }
  .articlehot{
    width: 100% !important;
  }
  
  .box-card {
    margin-bottom: 10px;
    width: 100%;
  }
}


.is-always-shadow {
  flex: 1;
}
#maintotal {
  // border: 1px solid #e0dbdb;
  border-radius: 4px;
  // margin-left: 5px;
  flex: 1.3;
}

.articlehot {
  // border: 1px solid #e0dbdb;
  border-radius: 4px;
  // margin-left: 4px;
  flex: 1.3;
}

.user_info {
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ccc;
  display: flex;
  align-items: center;
  img {
    margin-right: 40px;
    width: 150px;
    height: 150px;
    border-radius: 50%;
  }
  .userinfo {
    .name {
      font-size: 28px;
      margin-bottom: 10px;
    }
    .access {
      color: #9999;
    }
  }
}

.login-info {
  p {
    line-height: 28px;
    font-size: 18px;
    color: #9999;
    span {
      color: #666666;
      margin-left: 60px;
    }
  }
}
</style>
